﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DataObjectsPhone;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Phone.Net.NetworkInformation;
using System.Diagnostics;

namespace ee_wp_tourmaker.WebServices
{
    public class ChallengeServices
    {
        //it should have private webservice proxies here

        public void startDownloading()
        {
            bool isAvailable = NetworkInterface.GetIsNetworkAvailable();
            if (isAvailable == false)
            {
                Debug.WriteLine("No connection to download challenges");
            }
            else
            {
                var client = new ee_wp_tourmaker.AzureService.Service1Client();
                client.OpenCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_OpenCompleted);
                client.OpenAsync(client);
                client.GetChallengeListCompleted += new EventHandler<AzureService.GetChallengeListCompletedEventArgs>(client_GetChallengeListCompleted);
            }
        }

        void client_OpenCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            var client = (ee_wp_tourmaker.AzureService.Service1Client)e.UserState;

            client.GetChallengeListAsync(null, client);
        }

        void client_GetChallengeListCompleted(object sender, AzureService.GetChallengeListCompletedEventArgs e)
        {

            List<Challenge> array = new List<Challenge>();

            foreach (AzureService.ChallengeShort chal in e.Result)
            {
                if ( App.ChallengeData.ActiveChallenges.Any(q=> q.Id== chal.Id) || App.ChallengeData.DoneChallenges.Any(q=> q.Id==chal.Id))
                    continue;
                Challenge c = new Challenge();
                c.Name = chal.Name;
                c.Id = chal.Id;
                c.Checkpoints = chal.CheckPointCount;
                c.Points = chal.Points;

                array.Add(c);
            }

            App.ChallengeData.WebChallenges = array;
            App.MainModel.challengeBrowser.refreshWebList();
            ((AzureService.Service1Client)e.UserState).CloseAsync();
        }

    }
}
